<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Category extends MY_Controller {
	function __construct(){
		parent::__construct();
	}

	function admin_index(){
	 	$result = $this->categoryModel->get(array("order"=>"sort ASC"));
	 	$categories = array();
	 	if(!empty($result)){
		 	foreach ($result as $key => $value) {
		    $categories['items'][$value['id']] = $value;
		    $categories['parents'][$value['parent_id']][] = $value['id'];
		 	}
	 	}
		$this->_assign('categories',$categories);
		$this->_fetch('admin_index');
	}

	function admin_add(){
		$_post = $this->input->post();
		$this->load->model('tag_model','tagModel');
		if(empty($_post["submit"])){
			$tags = $this->tagModel->get();
			$this->_assign('tags',$tags);
			$cats = $this->categoryModel->get(array("order"=>"sort ASC"));
			$categories = array();
	 		if(!empty($cats)){
				foreach ($cats as $key => $value) {
			    $categories['items'][$value['id']] = $value;
			    $categories['parents'][$value['parent_id']][] = $value['id'];

			 	}
		  }
			//Assign
			$this->_assign('categories',$categories);
			//Fetch
			$this->_fetch('admin_add');
		}else{
			//Delete cache
			$this->cache->delete_folder("category");
			$this->cache->delete("menu_widget_html");

			if(!empty($_post["parent_id"])){

			}else{
				$_post["parent_id"] = 0;
			}
			if(!empty($_post["tag_name"])){
				$tag_name = explode("\n", $_post["tag_name"]);
				unset($_post["tag_name"]);
				foreach ($tag_name as $key => $value) {
					$tag_name[$key] = trim($value);

					$where["where"]["name"] = $tag_name[$key];

					$isThere = $this->tagModel->get($where);

					if(empty($isThere)){
						$dataInsert["name"] = $tag_name[$key];
						$dataInsert["url"] = Util::url_title($tag_name[$key]);
						$tag_id = $this->tagModel->add($dataInsert);
					}else{
						$tag_id = $isThere[0]["id"];
					}
					$_post["tag_id"] = $tag_id;
					$result = $this->categoryModel->add($_post);
				}
			}else{
				$result = $this->categoryModel->add($_post);
			}
			redirect(base_url("admin/category"));
		}
	}

	function admin_delete($id=""){
		if(empty($id)){
			show_404();
		}

		$deleteResult = $this->categoryModel->delete($id);

	 	//Delete cache
		$this->cache->delete_folder("category");
		$this->cache->delete("menu_widget_html");

	 	redirect(base_url("admin/category"));
	}

	function admin_orderupdate(){
		$_post = $this->input->post();
		foreach ($_post["sort"] as $key => $value) {
			$data["id"] = $key;
			$data["sort"] = $value;
			$this->categoryModel->add($data);
		}
		//Delete cache
		$this->cache->delete_folder("category");
		$this->cache->delete("menu_widget_html");
		redirect(base_url("admin/category"));
	}

	function index($start = 0){
		
		$this->load->library('pagination');
		$this->load->model('category_post_model','categoryPostModel');
		$this->load->model('images_model','imagesModel');
		$this->load->model('type_model','typeModel');
		
		//uri segment
		$total_uri = $this->uri->segment_array();	
		unset($total_uri[1]);
		$total_uri = array_values($total_uri);

		//Get Tag list
		$this->load->model("tag_model","tagModel");
		foreach ($total_uri as $key => $value) {
			if($start == $value AND $start != 0){
				unset($total_uri[$key]);
			}else{
				$total_uri[$key] = urldecode($value);
			}
			
		}
		$whereDirty["where_in"]["url"] = $total_uri;
		$categoryListDirty = $this->categoryModel->get($whereDirty);
		$whereClean["where"]["url"] = $total_uri[0];
		$categoryList = $this->categoryModel->get($whereClean);
		if(empty($categoryList)){
			show_404();
		}
		if(count($categoryListDirty) == 1 AND $categoryListDirty[0]["parent_id"] == 0){
			$whereCategoryPost["where"]["cat_id"] = $categoryList[0]["id"];
			$categoryTree = Util::getCategoryInherit($categoryList[0]["id"]);
		}else{
			$categoryListTree = Util::getCategoryInheritByParent($categoryList[0]["id"]);
			$resultFindCategoryTree = Util::findCategoryTree($categoryListDirty,$categoryListTree);
			$resultFindCategoryTree = array_values($resultFindCategoryTree);
			$whereCategoryPost["where"]["cat_id"] = $resultFindCategoryTree[count($resultFindCategoryTree)-1]["id"];
			$categoryTree = Util::getCategoryInherit($resultFindCategoryTree[count($resultFindCategoryTree)-1]["id"]);
		}

		if(!empty($categoryTree)){
			$categoryTree = array_reverse($categoryTree);
			foreach ($categoryTree as $key => $value) {
				$categoryTree["tree"][] = $value["name"];
				$categoryTree["treeUrl"][$key] = $value["url"];
				$categoryTree["treeForSubCategory"] = $value;
			}
			$this->_assign("categoryTree",$categoryTree["tree"]);
		}else{
			$this->_assign("categoryTree",array());
		}
		$subCategoryList = Util::getSubCategory($categoryTree["treeForSubCategory"]["id"]);
		$this->_assign("subCategoryList",$subCategoryList);
		$this->_assign("canonical",base_url("category/".implode("/",$categoryTree["treeUrl"])));

		$breadcrumb = "";
		foreach ($categoryTree["treeUrl"] as $key => $value) {
			$urlCat[] = $value;
			$breadcrumb .= " &raquo; <a href=\"".base_url("category/".implode("/", $urlCat))."\">".$categoryTree["tree"][$key]."</a>";
		}
		$this->_assign("breadcrumb",$breadcrumb);
		
		//pagination
		$config['prev_link'] = '&laquo;';
    $config['prev_tag_open'] = '<li>';
    $config['prev_tag_close'] = '</li>';

    $config['next_link'] = '&raquo;';
    $config['next_tag_open'] = '<li>';
    $config['next_tag_close'] = '</li>';

    $config['num_tag_open'] = '<li>';
    $config['num_tag_close'] = '</li>';

    $config['cur_tag_open'] = '<li class="active"><a href="#">';
    $config['cur_tag_close'] = '</a></li>';

    $config['first_tag_open'] = '<li>';
    $config['first_tag_close'] = '</li>';

    $config['last_tag_open'] = '<li>';
    $config['last_tag_close'] = '</li>';
		$config['base_url'] = base_url("category/".implode("/",$urlCat));
		$config['total_rows'] = $this->categoryPostModel->count_rows($whereCategoryPost);
		$config['per_page'] = 20;
		$config['uri_segment'] = $this->uri->total_segments();
		$this->pagination->initialize($config);

		$whereCategoryPost['limit']['amount'] = $config['per_page'];
		if($start > 0){
			$whereCategoryPost['limit']['start'] = $start;
		}else{
			$whereCategoryPost['limit']['start'] = 0;
		}

		$posts = $this->categoryPostModel->get($whereCategoryPost);
		if(!empty($posts)){
			foreach ($posts as $key => $value) {
				$posts[$key]["images"] = $this->imagesModel->get(array("where"=>array("pos_id"=>$value["id"])));
				$posts[$key]["categories"] = array_reverse(Util::getCategoryInherit($value["cat_id"]));
				$posts[$key]["province"] = Util::getProvince($posts[$key]["province"]);
				$posts[$key]["meta"] = Util::getPostMeta($posts[$key]["id"]);
				$posts[$key]["type"] = Util::getType($posts[$key]["typ_id"]);
				$posts[$key]["comment_count"] = Util::getCommentCount($posts[$key]["id"]);
			}
		}
		$this->_assign('posts',$posts);
		$this->_fetch('index');

	}

}